package com.jxlst.channel.pro.filter;


import com.jxlst.channel.pro.constant.CharacterDict;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * spring 拦截器重写，用于生成日志ID信息
 * <p>
 * 1、拦截器重写
 * </p>
 *
 * @author 香克斯
 * @version : 1.0
 * @date : 2017/11/29
 */
@Slf4j
public class BaseInterceptor extends HandlerInterceptorAdapter {


    /**
     * 请求系统时间Key，此key会放入想成变量中
     */
    private static final String REQ_TIME_KEY = "REQ_TIME_KEY";

    /**
     * This implementation always returns {@code true}.
     *
     * @param request  请求参数信息
     * @param response response对象
     * @param handler  对象信息
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //请求时间
        Long startIime = System.currentTimeMillis();
        MDC.put(REQ_TIME_KEY, startIime.toString());
        //设置请求和响应编码
        request.setCharacterEncoding(CharacterDict.UTF_8);
        response.setCharacterEncoding(CharacterDict.UTF_8);

        return super.preHandle(request, response, handler);
    }

    /**
     * 请求执行完成之后调用
     *
     * @param request  请求对象
     * @param response 返回对象
     * @param handler  处理对象
     * @param ex       异常
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

        //间隔时间，后续可根据此时间做监控
        Long intervalTime = (System.currentTimeMillis() - Long.parseLong(MDC.get(REQ_TIME_KEY)));
        String requestPath = request.getRequestURI();
        log.info("用户请求后台，地址：{}", requestPath);
        if (ex != null) {
            log.error("请求系统异常，异常内容：", ex);
        }
        log.info("本次请求总耗时：{}", intervalTime);
        MDC.clear();
    }
}
